package com.example.mydemo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.mydemo.entity.SysParam;
import com.example.mydemo.mapper.SysParamMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
    public class SysParamService {
        private final SysParamMapper sysParamMapper;
        private final RedisTemplate<String, String> redisTemplate;

        // 缓存键前缀
        private static final String CACHE_PREFIX = "sys:parm:";

        public SysParamService(SysParamMapper sysParamMapper, RedisTemplate<String, String> redisTemplate) {
            this.sysParamMapper = sysParamMapper;
            this.redisTemplate = redisTemplate;
        }

        /**
         * 根据参数编码获取参数值（优先缓存）
         */
        public String getParmValueByCode(String parmCode) {
            String cacheKey = parmCode;
            String cachedValue = redisTemplate.opsForValue().get(cacheKey);
            if (cachedValue != null) {
                return cachedValue;
            }

            SysParam sysParam = sysParamMapper.selectOne(
                    new QueryWrapper<SysParam>().eq("parm_code", parmCode)
            );

            if (sysParam != null) {
                redisTemplate.opsForValue().set(cacheKey, sysParam.getParamValue(), 1, TimeUnit.HOURS);
                return sysParam.getParamValue();
            }
            return null;
        }

        /**
         * 更新参数并清除缓存
         */
        @Transactional
        public boolean updateParmValue(String parmCode, String newValue) {
            SysParam sysParam = new SysParam();
            sysParam.setParamValue(newValue);
            int updateCount = sysParamMapper.update(
                    sysParam,
                    new UpdateWrapper<SysParam>().eq("parm_code", parmCode)
            );

            if (updateCount > 0) {
                redisTemplate.delete( parmCode);
                return true;
            }
            return false;
        }
    public boolean save(SysParam sysParam){
            return sysParamMapper.insert(sysParam)==1;
    }
    public List<SysParam> selectByName(String searchParams) {
            return sysParamMapper.selectByName(searchParams);
    }
}
